/**
 * 面向系统管理用户登录接口
 */
import md5 from 'md5';
import jwt from 'jsonwebtoken';
import * as tools from 'src-ssr/util/common';
import shortid from 'shortid';
// const forge = require('node-forge');
// import rsa from 'src-ssr/util/rsa';
import { Sequelize, Op } from 'sequelize';
import models from 'src-ssr/db/sequelize';
// const wechat = require('../util/wechat_enterprise');
// const dingtalk = require('../util/dingtalkSDK');
// const tools = require('../util/toolson');
// const OAuth = require('wechat-oauth');

/* 登录验证 */
export const verify = async (req, res) => {
  const { tenant, nickname, password } = req.body;

  // 禁止在租户端登录系统管理
  if (tenant === '系统管理') {
    return res.json({
      result: 'fail',
      message: '组织名称或用户名或密码错误'
    });
  }

  let tenantInfo = null;
  let tenantWhere = { id: 0 };
  if (tenant) {
    tenantWhere = {
      tenant_name: tenant,
      state: 1
    };
  }

  tenantInfo = await models.m_tenants.findOne({
    attributes: ['id', 'tenant_name'],
    where: tenantWhere,
    raw: true
  });

  if (!tenantInfo) {
    return res.json({
      result: 'fail',
      message: '组织名称或用户名或密码错误'
    });
  }

  const userInfo = await models.m_users.findOne({
    attributes: ['id', 'nickname', 'rights', 'headimg', 'password', 'salt'],
    include: [{
      model: models.m_roles,
      attributes: ['id', 'role_name']
    }],
    where: {
      nickname,
      tenant_id: tenantInfo.id
    },
    raw: true
  });

  if (!userInfo) {
    return res.json({
      result: 'fail',
      message: '组织名称或用户名或密码错误'
    });
  }

  const md5pwd = md5(password + userInfo.salt);
  if (md5pwd !== userInfo.password) {
    return res.json({
      result: 'fail',
      message: '组织名称或用户名或密码错误'
    });
  }

  // 更新登录数次
  tools.updateLogin(userInfo.id, tools.getIP(req), tenantInfo.id);
  // 密码验证成功后，生成token
  const token = jwt.sign({
    id: userInfo.id,
    nickname: userInfo.nickname,
    tid: tenantInfo.id
  },
  global.privateKey,
  { expiresIn: 7 * 24 * 60 * 60 });// token 7天过期

  // console.log(userInfo);

  res.json({
    result: 'ok',
    token,
    tenant: tenantInfo,
    user: {
      id: userInfo.id,
      nickname: userInfo.nickname,
      rights: userInfo.rights,
      headimg: userInfo.headimg
    },
    role: {
      id: userInfo['m_role.id'],
      role_name: userInfo['m_role.role_name']
    }
  });
}
